package com.samsung.database;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class PartesDBAdapter {

	private static final String DATABASE_NAME = "partes.db";
	private static final String TABLA_PARTES = "PARTES";
	private static final String TABLA_CELULARES = "CELULARES";
	private static final String TABLA_CONFIG = "CONFIG";
	private static final int DATABASE_VERSION = 1;
	private SQLiteDatabase myDataBase;
	private final Context myContext;
	

	public static final String KEY_ID = "_id";
	public static final String KEY_PARTE = "NRO_PARTE";
	public static final String KEY_CODIGO = "CODIGO";
	public static final String KEY_MODELO = "MODELO";
	
	public static final String KEY_CEL_ID = "ID";
	public static final String KEY_NUMERO = "NUMERO";
	
	public static final String KEY_DATO = "DATO";
	public static final String KEY_VALOR = "VALOR";
	
	public static final String KEY_CON_ID = "ID";
	
	
	
	public static final String KEY_NOMBRE_DESC = "NOMBRE_DESC";
	
	
	private static String DB_PATH = "/data/data/com.samsung/databases/";
	private static String DB_NAME = "partes.db";

	private DBOpenHelper dbHelper;

	public PartesDBAdapter(Context _context) {
		this.myContext = _context;
		dbHelper = new DBOpenHelper(myContext, DATABASE_NAME, null,
				DATABASE_VERSION);
		try {
        	createDataBase();
        } catch (IOException ioe) {
       	 throw new Error("Unable to create database");
        }
	}
	
	public long insertCelular(String numero){
		// Create a new row of values to insert.
		ContentValues newTaskValues = new ContentValues();
		// Se coloca los valores a cada  
		newTaskValues.put(KEY_NUMERO, numero); 
		
		// Insertando la fila 
		return myDataBase.insert(TABLA_CELULARES, null, newTaskValues);
	}
	
	public long updateCelular(String numero, int sec){
		// Create a new row of values to insert.
		ContentValues newTaskValues = new ContentValues();
		// Se coloca los valores a cada  
		newTaskValues.put(KEY_NUMERO, numero); 
			
		// Insertando la fila 
		return myDataBase.update(TABLA_CELULARES,newTaskValues,KEY_CEL_ID+"='"+sec+"'",null);
	}
	
	public long crearCelular(String numero,int sec){
		ContentValues newTaskValues = new ContentValues();
		// Se coloca los valores a cada  
		newTaskValues.put(KEY_NUMERO, numero); 
		newTaskValues.put(KEY_CEL_ID,sec);			
		// Insertando la fila 
		return myDataBase.insert(TABLA_CELULARES, null, newTaskValues);
	}
	
	public long updateRuta(String ruta){
		// Create a new row of values to insert.
		ContentValues newTaskValues = new ContentValues();
		// Se coloca los valores a cada  
		newTaskValues.put(KEY_CON_ID, 1);		
		newTaskValues.put(KEY_DATO, "RUTA");
		newTaskValues.put(KEY_VALOR, ruta);
			
		// Insertando la fila 
		return myDataBase.update(TABLA_CONFIG,newTaskValues,KEY_DATO+"='RUTA'",null);
	}
	
	public long crearRuta(String ruta){
		
		ContentValues newTaskValues = new ContentValues();
		// Se coloca los valores a cada  
		newTaskValues.put(KEY_CON_ID, 1);
		newTaskValues.put(KEY_DATO, "RUTA"); 
		newTaskValues.put(KEY_VALOR,ruta);			
		// Insertando la fila 
		
		return myDataBase.insert(TABLA_CONFIG, null, newTaskValues);
	}
	
	public boolean deleteCelular(String numero){
		return myDataBase.delete(TABLA_CELULARES, KEY_NUMERO + "=" + numero, null) > 0;
	}
	

	public boolean deleteCelularbyId(int sec){
		return myDataBase.delete(TABLA_CELULARES, KEY_CEL_ID + "='"+sec+"'", null) > 0;
	}
	
	public Cursor getCelulares() {

		return myDataBase.query(TABLA_CELULARES, new String[] { KEY_CEL_ID,
				KEY_NUMERO }, null,
				null, null, null, null);
		
		
	}
	
	public Cursor getRuta() {

		return myDataBase.query(TABLA_CONFIG, new String[] { KEY_CON_ID,
				KEY_DATO, KEY_VALOR }, KEY_DATO+"='RUTA'",
				null, null, null, null);
	}

	/**
	 * Creates a empty database on the system and rewrites it with your own
	 * database.
	 * */
	public void createDataBase() throws IOException {
		boolean dbExist = checkDataBase();
		if (!dbExist) {
			// By calling this method and empty database will be created into
			// the default system path
			// of your application so we are gonna be able to overwrite that
			// database with our database.
			dbHelper.getReadableDatabase();
			try {
				copyDataBase();
			} catch (IOException e) {
				throw new Error("Error copying database");
			}
		}
	}

	/**
	 * Check if the database already exist to avoid re-copying the file each
	 * time you open the application.
	 * 
	 * @return true if it exists, false if it doesn't
	 */
	private boolean checkDataBase() {
		SQLiteDatabase checkDB = null;
		try {
			String myPath = DB_PATH + DB_NAME;
			checkDB = SQLiteDatabase.openDatabase(myPath, null,
					SQLiteDatabase.OPEN_READONLY);

		} catch (SQLiteException e) {
			// database does't exist yet.
		}
		if (checkDB != null) {
			checkDB.close();
		}
		return checkDB != null ? true : false;
	}

	/**
	 * Copies your database from your local assets-folder to the just created
	 * empty database in the system folder, from where it can be accessed and
	 * handled. This is done by transfering bytestream.
	 * */
	private void copyDataBase() throws IOException {

		// Open your local db as the input stream
		InputStream myInput = myContext.getAssets().open(DB_NAME);

		// Path to the just created empty db
		String outFileName = DB_PATH + DB_NAME;

		// Open the empty db as the output stream
		OutputStream myOutput = new FileOutputStream(outFileName);

		// transfer bytes from the inputfile to the outputfile
		byte[] buffer = new byte[1024];
		int length;
		while ((length = myInput.read(buffer)) > 0) {
			myOutput.write(buffer, 0, length);
		}
		// Close the streams
		myOutput.flush();
		myOutput.close();
		myInput.close();
	}

	
	
	public void close() {
		myDataBase.close();
	}

	public void open() throws SQLiteException {
		try {
			myDataBase = dbHelper.getWritableDatabase();
		} catch (SQLiteException ex) {
			myDataBase = dbHelper.getReadableDatabase();
		}
	}
	
	public Cursor getPartesCursor(String modelo, String codigo) {
/*		return db.query(DATABASE_TABLE, new String[] { KEY_ID, KEY_CODIGO,
				KEY_NOMBRE_DESC }, null, null, null, null, null);*/
		
		return myDataBase.query(TABLA_PARTES, new String[] { 
				KEY_PARTE,KEY_CODIGO, KEY_MODELO,
				KEY_NOMBRE_DESC }, KEY_CODIGO +" = '"+ codigo +"' and " + 
				KEY_MODELO + " = '" + modelo + "'", null, null, null, null);
	}
	
	public Cursor getModelosCursor(){
		return myDataBase.query(true,TABLA_PARTES, new String[] { 
				KEY_MODELO},null,null, null, null, null,null);
		
	}
	
	
	private static class DBOpenHelper extends SQLiteOpenHelper {

		Context myContext;
		public DBOpenHelper(Context context, String name,
				CursorFactory factory, int version) {
			super(context, name, factory, version);
			myContext = context;
		}

		// SQL Statement to create a new database.
		private static final String DATABASE_CREATE = "create table "
				+ TABLA_PARTES + " (" + 
				KEY_ID + " integer primary key autoincrement, " +
				KEY_PARTE  + " text not null, " +
				KEY_CODIGO + " text not null, " +
				KEY_MODELO + " text not null, " +
				KEY_NOMBRE_DESC + " text not null);";

		@Override
		public void onCreate(SQLiteDatabase _db) {
			_db.execSQL(DATABASE_CREATE);
		}

		@Override
		public void onUpgrade(SQLiteDatabase _db, int _oldVersion,
				int _newVersion) {
			Log.w("TaskDBAdapter", "Upgrading from version " + _oldVersion
					+ " to " + _newVersion
					+ ", which will destroy all old data");
			// Drop the old table.
			_db.execSQL("DROP TABLE IF EXISTS " + TABLA_PARTES);
			// Create a new one.
			onCreate(_db);
		}
	
		
	}

}
